<template>
	<view class="my_form">
		<!-- 标题 -->
		<text class="title main-font-color font-weight-bold">{{titles[second_category_index]}}</text>
		<!-- 添加图片组件 -->
		<my-upload-image ref="myUploadImage"></my-upload-image>
		<!-- 提示 -->
		<view class="tips"
			v-if="second_category_index == 0 || second_category_index == 1 || second_category_index == 3">
			<uni-icons type="info" size="20"></uni-icons>
			<text>所上传的图片仅用作识别辅助填表，不会发布出去。PS: 识别的图片请确保为竖版，横板暂时识别不了，请谅解。</text>
		</view>
		<!-- 内容表单 -->
		<uni-forms ref="form" :model="formData" validateTrigger="bind" err-show-type="undertext">

			<uni-forms-item v-for="(item, index) in input_info[second_category_index]" :key="index" :label="item.label"
				:name="item.name">

				<uni-easyinput v-model="formData[item.name]" :type="item.type" :trim="item.trim"
					:placeholder="item.placeholder"></uni-easyinput>

			</uni-forms-item>
			<!-- 提交按钮 -->
			<button :class="[disabled?'disable':'submit_btn']" :disabled="disabled" hover-class="btn-click"
				@click="submit_info">{{btnText}}</button>
		</uni-forms>
	</view>
</template>

<script>
	import myUploadImage from '@/components/myUploadImage/myUploadImage.vue'

	const app = getApp()

	import {
		mapState,
		mapMutations
	} from 'vuex'

	export default {
		name: "myForm",
		options: {
			styleIsolation: 'shared',
		},
		components: {
			myUploadImage
		},
		data() {
			return {
				// 需要更新的_id
				update_id: '',
				// 发布按钮是否可以点击
				disabled: true,
				// 标题
				titles: ['校园卡', '身份证', '电影卡', '银行卡', '其他物品', '其他物品'],
				// input的显示数据
				input_info: [
					// 0 校园卡类型
					[{
						label: '学生名字',
						name: 'student_name',
						type: 'text',
						maxlength: 4,
						trim: 'all',
						placeholder: '请输入学生名字'
					}, {
						label: '学号',
						name: 'student_ID',
						type: 'number',
						maxlength: 11,
						trim: 'all',
						placeholder: '请输入学号'
					}, {
						label: '取回地点',
						name: 'location',
						type: 'text',
						maxlength: 30,
						trim: 'both',
						placeholder: '请输入失主取回失物的地点'
					}, {
						label: '联系方式',
						name: 'contact_way',
						type: 'text',
						maxlength: 50,
						trim: 'both',
						placeholder: '请输入联系方式'
					}],
					// 1 身份证类型
					[{
						label: '学生名字',
						name: 'student_name',
						type: 'text',
						maxlength: 4,
						trim: 'all',
						placeholder: '请输入学生名字'
					}, {
						label: '身份证号',
						name: 'ID_card_No',
						type: 'number',
						maxlength: 18,
						trim: 'all',
						placeholder: '请输入身份证号'
					}, {
						label: '取回地点',
						name: 'location',
						type: 'text',
						maxlength: 30,
						trim: 'both',
						placeholder: '请输入失主取回失物的地点'
					}, {
						label: '联系方式',
						name: 'contact_way',
						type: 'text',
						maxlength: 50,
						trim: 'both',
						placeholder: '请输入联系方式'
					}],
					// 2 电影卡
					[{
						label: '电影卡号',
						name: 'movie_card_No',
						type: 'number',
						maxlength: 12,
						trim: 'all',
						placeholder: '请输入电影卡号'
					}, {
						label: '取回地点',
						name: 'location',
						type: 'text',
						maxlength: 30,
						trim: 'both',
						trim: 'all',
						placeholder: '请输入失主取回失物的地点'
					}, {
						label: '联系方式',
						name: 'contact_way',
						type: 'text',
						maxlength: 50,
						trim: 'both',
						placeholder: '请输入联系方式'
					}],
					// 3 银行卡
					[{
						label: '银行名字',
						name: 'bank_card_name',
						type: 'text',
						maxlength: 10,
						trim: 'all',
						placeholder: '请输入银行名字'
					}, {
						label: '银行卡号',
						name: 'bank_card_No',
						type: 'number',
						maxlength: 19,
						trim: 'all',
						placeholder: '请输入银行卡号'
					}, {
						label: '取回地点',
						name: 'location',
						type: 'text',
						maxlength: 30,
						trim: 'both',
						placeholder: '请输入失主取回失物的地点'
					}, {
						label: '联系方式',
						name: 'contact_way',
						type: 'text',
						maxlength: 50,
						trim: 'both',
						placeholder: '请输入联系方式'
					}],
					// 4 其它物品lost
					[{
						label: '物品名称',
						name: 'item_name',
						type: 'text',
						maxlength: 20,
						trim: 'all',
						placeholder: '请输入物品名称'
					}, {
						label: '物品描述',
						name: 'description',
						type: 'textarea',
						maxlength: 100,
						trim: 'both',
						placeholder: '请输入物品详情'
					}, {
						label: '取回地点',
						name: 'location',
						type: 'text',
						maxlength: 30,
						trim: 'both',
						placeholder: '请输入失主取回失物的地点'
					}, {
						label: '联系方式',
						name: 'contact_way',
						type: 'text',
						maxlength: 50,
						trim: 'both',
						placeholder: '请输入联系方式'
					}],
					// 5 其它物品found
					[{
						label: '物品名称',
						name: 'item_name',
						type: 'text',
						maxlength: 20,
						trim: 'all',
						placeholder: '请输入物品名称'
					}, {
						label: '物品描述',
						name: 'description',
						type: 'textarea',
						maxlength: 100,
						trim: 'both',
						placeholder: '请输入物品详情'
					}, {
						label: '丢失地点',
						name: 'location',
						type: 'text',
						maxlength: 30,
						trim: 'both',
						placeholder: '请输入可能丢失的地点'
					}, {
						label: '联系方式',
						name: 'contact_way',
						type: 'text',
						maxlength: 50,
						trim: 'both',
						placeholder: '请输入联系方式'
					}]
				],
				// 表单数据
				formData: {
					student_name: '',
					student_ID: '',
					location: '',
					contact_way: '',
					ID_card_No: '',
					movie_card_No: '',
					bank_card_name: '',
					bank_card_No: '',
					item_name: '',
					description: ''
				},
				// 临时的图片路径
				temp_image_url: [],
				// 图片的云存储ID
				cloud_image_url: '',
				// 提交的时间戳
				post_time: 0,
				// 当前用户的信息
				userInfo: {},
				// 调用云函数发布的名字
				cloudFuns: ['submit_campusCard_info', 'submit_IDCard_info', 'submit_movieCard_info',
					'submit_bankCard_info', 'submit_otherItem_info', 'submit_otherItem_info'
				],
				// 规则
				rules: {
					// 校园卡和身份证的字段规范
					student_name: {
						rules: [{
							minLength: 2,
							maxLength: 4,
							errorMessage: '请输入合法的学生名字'
						}]
					},
					// 学号
					student_ID: {
						rules: [{
							validateFunction: (rules, value, data, callback) => {
								if (value.length != 11) {
									callback('合法的学号为11位')
								}
								return true
							}
						}]
					},
					// 取回地点
					location: {
						rules: [{
							maxLength: 30,
							errorMessage: '地址不得超过 {maxLength} 个字'
						}]
					},
					// 联系方式
					contact_way: {
						rules: [{
							maxLength: 50,
							errorMessage: '联系方式不得超过 {maxLength} 个字'
						}]
					},
					// 身份证号
					ID_card_No: {
						rules: [{
							validateFunction: (rules, value, data, callback) => {
								if (value.length != 18) {
									callback('合法的身份证号为18位')
								}
								return true
							}
						}]
					},
					// 电影卡号
					movie_card_No: {
						rules: [{
							validateFunction: (rules, value, data, callback) => {
								if (value.length != 12) {
									callback('合法的电影卡号为12位')
								}
								return true
							}
						}]
					},
					// 银行名字
					bank_card_name: {
						rules: [{
							minLength: 2,
							maxLength: 10,
							errorMessage: '银行名字需 {minLength} 到 {maxLength} 字'
						}]
					},
					// 银行卡号
					bank_card_No: {
						rules: [{
							validateFunction: (rules, value, data, callback) => {
								if (value.length != 19) {
									callback('合法的银行卡号为19位')
								}
								return true
							}
						}]
					},
					// 物品名称
					item_name: {
						rules: [{
							maxLength: 20,
							errorMessage: '物品名称不得超过 {maxLength} 个字'
						}]
					},
					// 物品描述
					description: {
						rules: [{
							maxLength: 100,
							errorMessage: '物品描述不得超过 {maxLength} 个字'
						}]
					},
				},
			};
		},
		props: {
			// 按钮的文字
			btnText: {
				type: String,
				default: '发布'
			},
		},
		computed: {
			// 映射状态管理的state
			...mapState({
				// 当前第一大类的选择状态
				first_category_index: state => state.first_category_index,
				// 当前第二大类的选择状态
				second_category_index: state => state.second_category_index
			})
		},
		methods: {
			// 清空数据
			reset() {
				this.formData.student_name = ''
				this.formData.student_ID = ''
				this.formData.location = ''
				this.formData.contact_way = ''
				this.formData.ID_card_No = ''
				this.formData.movie_card_No = ''
				this.formData.bank_card_name = ''
				this.formData.bank_card_No = ''
				this.formData.item_name = ''
				this.formData.description = ''
			},
			// 映射状态管理的mutations
			...mapMutations(['edit_first_index', 'edit_second_index']),
			// 校园卡信息提交
			submit_info_cloudFun(image = '') {
				wx.cloud.callFunction({
					name: this.cloudFuns[this.second_category_index],
					data: {
						UID: this.userInfo.profile.student_ID,
						post_time: this.post_time,
						formData: this.formData,
						nickname: this.userInfo.nickname,
						avatarUrl: this.userInfo.avatarUrl,
						image,
						second_category_index: this.second_category_index,
						userID: this.userInfo.userID
					}
				}).then(res => {
					console.log(res);
					this.unshift_id(res.result._id)
				})
			},

			// 将返回来的_id添加到个人数据库里
			unshift_id(_id) {
				wx.cloud.callFunction({
					name: 'unshift_id',
					data: {
						_id,
						UID: this.userInfo.profile.student_ID
					}
				}).then(res => {
					console.log(res);
					uni.hideLoading()
					uni.showToast({
						title: '发布成功',
						icon: 'success'
					})
					// 清空数据
					this.reset()
					this.temp_image_url = []
					this.$refs.myUploadImage.temp_image_url = []
				})
			},

			// 上传图片
			upload_form_image() {
				console.log('上传图片');
				// 随机生成云存储的图片名字
				const prename = app.uuid()
				const imgFormat = this.temp_image_url[0].substring(this.temp_image_url[0].indexOf('.'))
				const imgName = prename + imgFormat
				// 上传头像图片
				wx.cloud.uploadFile({
					cloudPath: `published_images/${this.userInfo.profile.student_ID}/${imgName}`,
					filePath: this.temp_image_url[0]
				}).then(res => {
					console.log(res);
					if (this.btnText == '发布') {
						// 调用云函数
						this.submit_info_cloudFun(res.fileID)
					} else if (this.btnText == '更新') {
						this.update_edit_info(res.fileID)
					}
				})
			},

			// 更新数据，在edit页面
			update_edit_info(image = '') {
				wx.cloud.callFunction({
					name: 'update_edit_info',
					data: {
						_id: this.update_id,
						formData: this.formData,
						image,
						second_category_index: this.second_category_index
					}
				}).then(res => {
					console.log(res);
					// 清空数据
					this.reset()
					this.temp_image_url = []
					this.$refs.myUploadImage.temp_image_url = []
					uni.hideLoading()
					uni.showToast({
						title: '更新成功',
						icon: 'success'
					})
					// 完成的时候跳转页面的效果
					setTimeout(() => {
						uni.navigateBack()
						setTimeout(() => {
							uni.startPullDownRefresh()
						}, 300)
					}, 1000)
				})
			},

			// 提交按钮
			submit_info() {
				uni.showLoading({
					title: '加载中...'
				})
				// 获取提交的时间
				this.post_time = new Date().getTime()
				this.$refs.form.validate().then(res => {
					console.log('表单数据信息：', res);
					if (this.btnText == '发布') {

						// 根据类型来决定调用云函数
						if (this.second_category_index == 2 || this.second_category_index == 4 || this
							.second_category_index == 5) {
							// 如果是电影卡，其他物品类别，则需要先上传图片后再发布
							this.upload_form_image()
						} else {
							this.submit_info_cloudFun()
						}

					} else if (this.btnText == '更新') {

						// 根据类型来决定调用云函数
						if (this.temp_image_url.length == 0) {
							this.update_edit_info()
						} else {
							// 如果是电影卡，其他物品类别，则需要先上传图片后再发布
							this.upload_form_image()
						}

					}

				}).catch(err => {
					console.log('表单错误信息：', err);
					uni.showToast({
						title: '表单格式错误',
						icon: "error"
					})
				})
			},

		},
		// 监听器
		watch: {
			// 监听电影卡和其他物品是否有图片
			temp_image_url: {
				handler(newValue) {
					switch (this.second_category_index) {
						// 电影卡
						case 2:
							if (this.formData.movie_card_No && this.formData.location && this.formData.contact_way &&
								newValue.length != 0) {
								this.disabled = false
							} else {
								this.disabled = true
							}
							break
							// 其它物品lost和found
						case 4:
							if (this.formData.item_name && this.formData.description && this.formData.location && this
								.formData.contact_way && newValue.length != 0) {
								this.disabled = false
							} else {
								this.disabled = true
							}
							break
						case 5:
							if (this.formData.item_name && this.formData.description && this.formData.location && this
								.formData.contact_way && newValue.length != 0) {
								this.disabled = false
							} else {
								this.disabled = true
							}
							break
					}
				}
			},

			// 监听formData里面数据的变化
			formData: {
				handler(newValue) {
					switch (this.second_category_index) {
						// 校园卡
						case 0:
							if (newValue.student_name && newValue.student_ID && newValue.location && newValue
								.contact_way) {
								this.disabled = false
							} else {
								this.disabled = true
							}
							break
							// 身份证
						case 1:
							if (newValue.student_name && newValue.ID_card_No && newValue.location && newValue
								.contact_way) {
								this.disabled = false
							} else {
								this.disabled = true
							}
							break
							// 电影卡
						case 2:
							if (newValue.movie_card_No && newValue.location && newValue.contact_way && this.temp_image_url
								.length != 0) {
								this.disabled = false
							} else {
								if (this.formData.movie_card_No && this.formData.location && this.formData.contact_way &&
									this.btnText == '更新') {
									this.disabled = false
								} else {
									this.disabled = true
								}
							}
							break
							// 银行卡
						case 3:
							if (newValue.bank_card_name && newValue.bank_card_No && newValue.location && newValue
								.contact_way) {
								this.disabled = false
							} else {
								this.disabled = true
							}
							break
							// 其它物品lost和found
						default:
							if (newValue.item_name && newValue.description && newValue.location && newValue.contact_way &&
								this.temp_image_url.length != 0) {
								this.disabled = false
							} else {
								if (newValue.item_name && newValue.description && newValue.location && newValue
									.contact_way &&
									this.btnText == '更新') {
									this.disabled = false
								} else {
									this.disabled = true
								}
							}
							break
					}

				},
				// 监听对象里面的所有属性
				deep: true
			},
			// 监听第二大类的改变
			second_category_index(newValue, oldValue) {
				if (newValue != oldValue) {
					this.reset()
				}
			}
		},
		mounted() {
			// 设置表单的规则
			this.$refs.form.setRules(this.rules)
			this.userInfo = app.globalData.userInfo
		}
	}
</script>

<style scoped lang="scss">
	.my_form {
		width: 700rpx;
		box-sizing: border-box;
		padding: 30rpx;
		box-shadow: 0 0 8px #b8b8b8;
		background-color: white;
		border-radius: 26rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		margin-bottom: 50rpx;

		.title {
			font-size: 40rpx;
			width: 630rpx;
		}

		// 提示
		.tips {
			width: 600rpx;
			background-color: #fffbe8;
			display: flex;
			position: relative;
			padding: 10rpx;
			box-sizing: border-box;
			margin-bottom: 16rpx;

			text {
				font-size: 28rpx;
				color: #CB6928;
			}
		}

		button::after {
			border: none;
		}

		// 发布按钮可点击样式
		.submit_btn {
			background-color: #007aff;
			color: white;
			width: 600rpx;
			height: 80rpx;
			border-radius: 10rpx;
			line-height: 80rpx;
			margin-top: 20rpx;
		}

		// 发布按钮不可点击样式
		.disable {
			background-color: #7db1ff;
			color: white;
			width: 600rpx;
			height: 80rpx;
			border-radius: 10rpx;
			line-height: 80rpx;
			margin-top: 20rpx;
		}
	}

	// -------  以下是更改uni内置组件的样式  --------

	// 更改uni的icon组件样式
	/deep/ .uniui-info {
		position: static;
		color: #CB6928 !important;
		margin-right: 10rpx;
	}

	// 更改uni的iform和nput组件样式
	// 表单大盒子
	/deep/ .uni-forms-item__inner {
		width: 600rpx;
		display: flex;
		flex-direction: column;
		padding: 0;
		margin-bottom: 30rpx;
		// background-color: antiquewhite;
	}

	// 标题
	/deep/ .uni-forms-item__label {
		width: 200rpx !important;
		padding: 0;
	}

	/deep/ .label-text {
		font-size: 36rpx !important;
		font-weight: bold;
		color: #8C8C8C !important;
	}

	// 输入框
	// input的大外框
	/deep/ .uni-easyinput {
		border-color: #CDCDCD;
		border-radius: 10rpx;
		transition-property: border;
		transition-duration: .3s;
	}

	// input的外框
	/deep/ .uni-easyinput__content {
		width: 600rpx;
		height: 74rpx;
	}

	/deep/ .is-textarea {
		width: 600rpx;
		height: 160rpx;
	}

	// input的placeholder内容
	/deep/ .uni-easyinput__placeholder-class {
		font-size: 32rpx;
		color: #C7C7C7;
	}

	// input里面文字内容
	/deep/ .uni-easyinput__content-input {
		font-size: 32rpx;
		color: #504F54;
	}

	// input的错误提示内容
	/deep/ .uni-error-message {
		padding-left: 0 !important;
		position: absolute;
		bottom: -40rpx;
	}

	/deep/ .uni-error-message-text {
		font-size: 28rpx;
	}

	// 清除按钮
	/deep/ .uniui-clear {
		font-size: 36rpx !important;
	}

	// textarea的样式
	/deep/ .uni-easyinput__content-textarea {
		font-size: 32rpx;
		height: 140rpx;
		padding: 6rpx 0 6rpx 10rpx;
		box-sizing: border-box;
	}
</style>
